<?php
namespace control;
/*
*调岗记录类
*/

class jobApplyClass extends adIndexClass
{
    private const page = 'jobApply';
    private const table = 'job_apply';
    private const title = '调岗记录';
    private array $typeOption = ['仅调薪','仅调岗','调岗调薪'];
    public array $stateOption = ['草稿', '审核中', '已通过'];

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "姓名"     => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']),
                    '部门' => selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200']),
                ],
                [
                    '职位'   => selectMultiple(["name" => "jobId", 'table' => " job", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200']),
                    "生效日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(["name" => "state", 'option' => $this->stateOption]),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        $url = root . "control/adIndex.html?cla=" . self::page;
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'      => [
                        'name'  => '单据编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name' => [
                        'name'  => '姓名',
                        'width' => 100,
                    ],
                    'type'  => [
                        'name'  => '类型',
                        'width' => 100,
                    ],
                    'department'         => [
                        'name'  => '原部门',
                        'width' => 150,
                    ],
                    'job'          => [
                        'name'  => '原职位',
                        'width' => 150,
                    ],
                    'applyDepartment'          => [
                        'name'  => '申请调到部门',
                        'width' => 150,
                    ],
                    'applyJob'          => [
                        'name'  => '申请调到职位',
                        'width' => 150,
                    ],
                    'manager'          => [
                        'name'  => '直属上级',
                        'width' => 100,
                    ],
                    'salaryText'          => [
                        'name'  => '调薪说明',
                        'width' => 150,
                    ],
                    'startDate'          => [
                        'name'  => '生效日期',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 100,
                    ],
                ];
        }
        return $tr;
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//试卷编号
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),//状态
            "staffId" => $this->post('stid'),//姓名
            "oldJobId" => $this->post('jobId'),//职位
        );
        $and = $this->seeSelf(self::page);
        if (!empty($this->post('departmentId'))){
            //部门
            $and.=" and oldJobId in (select id from job where departmentId = '{$this->post('departmentId')}')";
        }
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'),field: 'startDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" =>$orderBy['orderBy']));
        //获取表头
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
            );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => $array['state'] == '草稿' ? array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})") : [],
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            $manager= query('staff', " stid = '$array[managerId]'");
            $job = query('job', " id = '$array[oldJobId]'");
            $applyJob = query('job', " id = '$array[jobId]'");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "name":
                        $talent_pool = query('talent_pool'," id = '$array[talentId]'");
                        $row[] = $talent_pool['name'];
                        break;
                    case "department":
                        $row[] = departmentClass::getTypeName($job['departmentId']);
                        break;
                    case "job":
                        $row[] = $job['name'];
                        break;
                    case "applyDepartment":
                        $row[] = departmentClass::getTypeName($applyJob['departmentId']);
                        break;
                    case "applyJob":
                        $row[] = $applyJob['name'];
                        break;
                    case "manager":
                        $row[] = $manager['name'];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*编辑职位基本信息-弹出层*/
    public function edit()
    {
        $id =  $this->post('id')?:suiji();
        $info = query(self::table, " id = '" .$id . "' ");
        $job = query('job', " id = '$info[oldJobId]'");
        $jobName = departmentClass::getTypeName($job['departmentId']).'-'.$job['name'];
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . "员工：" => selectMultiple(["name" => "staffId", 'table' => " staff",'where'=>"state !='离职' and stid not in (select stid from user where isDel = 1)", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => '姓名', 'change' => 'getStaffInfo', 'class' => 'text', "value" => $info['staffId']]),
                    "原职位：" => "<span id='oldJob'>{$jobName}</span>",
                ],
                [
                    must."申请类型："=>radio(array('name'=>'type','value'=>$this->typeOption,'change'=>'showField','checked'=>$info['type']?:$this->typeOption[0])),
                    must . "生效日期：" => text(["name" => "startDate", 'laydate' => [], 'class' => 'text', "value" => $info['startDate']]),
                ],
                [
                    "申请职位：" => selectMultiple(["name" => "jobId", 'table' => " job", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => '申请职位', "value" => $info['jobId']]),
                    "直属上级：" => selectMultiple([
                        "name" => "managerId", "title" => "直属上级",
                        'value' => $info['managerId'],
                        'sqlField' => 'name',
                        'sqlId' => 'stid',
                        'table' => "staff",
                        'where'=>"state !='离职' order by time asc"
                    ]),
                ],
                [
                    "调薪说明：" => textarea(array('name' => 'salaryText', 'value' => $info['salaryText'])),
                ],
                [
                    "备注：" => textarea(array('name' => 'text', 'value' => $info['text'])),
                ],
                [
                    "附件：" =>fileUploadClass::addFileComponent($info['id'],'调岗记录',self::page,self::page.'EditForm'),
                ],
            ],
        ]);
        $html .= <<<efo

<script>
        function getStaffInfo(e){
            $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getStaffInfo',{id:e.value},function (res){
                $("#oldJob").html(res.data.oldJob);
            },'json')
        }
        function showField(e){
            let type = $("form[name='jobApplyEditForm'] [type='radio']:checked").val();
            if (type =='仅调岗'){
                $("[name='salaryText']").parent().parent().hide();
                 $("[name='jobId']").parent().parent().parent().show();
                $("[name='managerId']").parent().parent().parent().show();
            }else if(type=='仅调薪'){
                $("[name='jobId']").parent().parent().parent().hide();
                $("[name='managerId']").parent().parent().parent().hide();
                $("[name='salaryText']").parent().parent().show();
            }else{
                 $("[name='salaryText']").parent().parent().show();
                  $("[name='jobId']").parent().parent().parent().show();
                $("[name='managerId']").parent().parent().parent().show();
            }
        }
        $(function (){
            showField()
        })
</script>


efo;
        //返回
        return $this->layer(array("title" => L('job.button.editor'), "height" => 420, "html" => $html));
    }

    /**
     *获取员工信息
     */
    public function getStaffInfo()
    {
        $staff = query('staff', " stid = '{$this->post('id')}'");
        $job = query('job', " id = '$staff[jobId]'");
        $json['data'] = [
            'oldJob' =>  departmentClass::getTypeName($job['departmentId']).'-'.$job['name'],
        ];
        return json_encode($json, 320);
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        //附件
        $fileIdArr = $this->post('fileId');
        $field = [
            'staffId' => $this->post('staffId'),
            'startDate' => $this->post('startDate'),
            'jobId' => $this->post('jobId'),
            'type' => $this->post('type'),
            'salaryText' => $this->post('salaryText'),
            'managerId' => $this->post('managerId'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'staffId' => '姓名',
            'type' => '申请类型',
            'startDate' => '生效日期',
        ];
        $rules = [
            'staffId' => 'required',
            'type' => 'required',
            'startDate' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $staff = query('staff', " stid = '$field[staffId]'");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        }elseif($field['type'] !='仅调薪' && $staff['jobId'] == $field['jobId']){
            $json['warn'] = '申请职位不可与当前职位相同';
        }elseif($field['type'] !='仅调薪' && empty($field['jobId'])){
            $json['warn'] = '请选择调岗的职位';
        } else {
            $field['talentId'] = $staff['talentId'];
            $field['oldJobId'] = $staff['jobId'];
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $department = query('department', " id = '{$this->controlJob['departmentId']}'");
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'TGSQ' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'stid' => $this->control['stid'],
                    'deptName' => $department['name'],
                    'state' => '草稿',
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加主表ID到附件表
                if (is_array($fileIdArr)) {
                    update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }
    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button=[];
          if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'],'selfChoose')) {
            $button[] = [
                "name" => '提交审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name'=>'调岗申请',
                    'table' => self::table,
                    'process' => [
                        // 预览函数
                        'detail' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],
                        // 保存函数
                        'save' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'editEdit'
                        ],
                        //执行发起时验证函数
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
// 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'],  'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => '审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿', '已通过'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => "finish",
                            'data'=>['id'=>$info['id']]
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'],'cancel') && $info['state'] == '审核中') {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                 "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
//                     当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }
    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                "title" => self::title . '详情',
            );
            $talent_pool = query('talent_pool'," id = '$info[talentId]'");
            $job = query('job', " id = '$info[oldJobId]'");
            $applyJob = query('job', " id = '$info[jobId]'");
            $button = [];
            if ($this->power(self::page, "edit") && $info['state'] =='草稿') {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                ];
            }
            if ($this->power(self::page, "del") && $info['state'] =='草稿') {
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            $audit = query('audit'," targetId = '$info[id]'");
            $manager = query('staff',"stid = '$info[managerId]'");
            //审核按钮
            $button = array_merge($this->auditButton($info),$button);
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "基本信息" => array(
                    array(
                        "姓名" => $talent_pool['name'],
                        "申请类型"=>$info['type'],
                        "原职位" => departmentClass::getTypeName($job['departmentId']).'->'.$job['name'],
                        "申请职位" =>  $applyJob['name'] ? departmentClass::getTypeName($applyJob['departmentId']).'->'.$applyJob['name'] : '-',
                    ),
                    array(
                        "生效日期" => $info['startDate'],
                        "直属上级"=>$manager['name']
                    ),
                    array(
                        "调薪说明" => pre($info['salaryText']),
                    ),
                    array(
                        "备注" => pre($info['text']),
                    ),
                ),
                '系统信息' => array(
                    array(
                        "单据编号" => $info['orderNo'],
                        "申请人部门" => $info['deptName'],
                        "申请人" => self::findStaff($info['stid']),
                        "创建时间" => $info['time'],
                    ),
                    array(
                        "提交时间" => self::null($audit['commitTime']),
                        "状态" => $info['state'],
                    ),
                ),
                '附件' => array(
                    array(
                         fileUploadClass::showFile($info['id'], '调岗记录')
                    )
                ),
                '流程'=>array(
                    array(
                        auditClass::auditRecord(self::table,$info['id'])
                    )
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 审批结束后需要执行的操作
     * @param $data
     */
    public function finish($data){
        $info = query(self::table," id = '$data[id]'");
        //员工表
        $staff = query('staff'," stid = '{$info['staffId']}'");
        //如果转正日期小于等于当前日期，立即转正
        if (strtotime($info['startDate']) <= time()){
            $field = [
                'jobId'=>$info['jobId']
            ];
            if ($info['managerId']){
                $field['manager'] = $info['managerId'];
            }
            update(array('table'=>'staff','field'=>$field,'where'=>" stid ='$staff[stid]'"));
            update(array('table'=>self::table,'field'=>array('confirmDate'=>$this->date),'where'=>"id ='$info[id]'"));
            //生成员工变动记录
            $obj = new staffEntryRecordClass();
            $obj->insertStaffStateRecord($staff['stid'],'调岗',$info['id'],$this->date);
        }
    }
    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page. 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn = "不是草稿状态，暂不能删除";
                } else {
                    //删除audit表记录
                    delete(array('table'=>'audit','where'=>"targetId = '$id'"));
                    $all = find(array('table'=>'file','where'=>"targetId = '$id'"));
                    foreach ($all['array'] as $val){
                        fileDelete($val['src']);
                        delete(array("table" =>'file', "where" => " id = '$val[id]' "));
                    }
                    //删除审批记录
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message", "where" => " typeId = '$id' "));
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}

